package com.onluy.framework.system.converter;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.onluy.framework.tools.utils.JsonUtil;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.util.StreamUtils; 

public class JsonHttpMessageConverter extends FastJsonHttpMessageConverter
{
  protected Logger log = LoggerFactory.getLogger(getClass());

  private SerializerFeature[] serializerFeatures = { SerializerFeature.WriteDateUseDateFormat };

  @Autowired
  private HttpServletRequest request;

  protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { String text = "{}";
    if ((obj instanceof List)) {
      List dataset = (List)obj;
      String actionType = this.request.getParameter("__actionType");

      if ("export".equals(actionType)) {
        try {
          HttpServletResponse response = ((ServletServerHttpResponse)outputMessage).getServletResponse();
          String exportName = this.request.getParameter("exportName");
          //ExportUtil.exportExcel(this.request, response, dataset, this.request.getParameter("headerJSON"), StringUtils.isEmpty(exportName) ? "exportfile" : exportName);
        } catch (Exception e) {
          this.log.error(e.getMessage(), e);
        }
        return;
      }

      if ("expand".equals(actionType)) {
        text = JsonUtil.toJson(dataset);
      }
      else
      {
        text = JSON.toJSONString(obj, getFeatures());
      }
    } else {
      text = JSON.toJSONString(obj, getFeatures());
    }

    if ("true".equals(this.request.getParameter("JQUERY_FORM_AJAX_REQUEST"))) {
      MediaType mediaType = new MediaType(MediaType.TEXT_HTML.getType(), MediaType.TEXT_HTML.getSubtype(), getCharset());
      outputMessage.getHeaders().setContentType(mediaType);
    }

	log.info("===============JsonHttpMessageConverter.text:"+text); 
    StreamUtils.copy(text, getCharset(), outputMessage.getBody());
  }

  public SerializerFeature[] getFeatures()
  {
    return this.serializerFeatures;
  }
}